<template>
  <!-- 创建新租表单第三步 - 补充表单资料 -->
  <div class="container">
    <CommonTitle :titleName="'合同模板'"></CommonTitle>
    <el-card class="card-box">
      <el-form :inline="true" ref="elFormRef" :rules="rules" :model="form" label-width="120px">
          <el-row>
              <el-col :span="8">
                  <el-form-item label="合同名称" prop="contractName">
                      <el-input  class="common-width" v-model="form.contractName" placeholder="请输入合同名称"/>
                  </el-form-item>
              </el-col>
              <el-col :span="8">
                  <el-form-item label="项目集" prop="projectSetId">
                      <el-select
                              filterable
                              v-model="form.projectSetId"
                              @change="projectSetIdChange"
                              clearable
                              placeholder="请选择项目集"
                      >
                          <el-option
                                  v-for="(item, index) in projectSetList"
                                  :key="index"
                                  :label="item.projectSetName"
                                  :value="item.projectSetId"
                          ></el-option>
                      </el-select>
                  </el-form-item>
              </el-col>
              <el-col :span="8">
                  <el-form-item label="所属项目" prop="projectId">
                      <el-select
                              filterable
                              v-model="form.projectId"
                              clearable
                              @change="changeProject"
                              :disabled="form.projectSetId===''"
                      >
                          <el-option
                                  v-for="(item, index) in projectList"
                                  :key="index"
                                  :label="item.projectName"
                                  :value="item.projectId"
                          ></el-option>
                      </el-select>
                  </el-form-item>
              </el-col>
          </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="任务来源" prop="meetingTitle">
              <el-input v-model="form.meetingTitle" class="common-width" placeholder="请输入任务来源"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.contractTemplateId!=5">
            <el-form-item label="新签/续签">
              <el-select disabled class="common-width" v-model="form.signType" placeholder="请选择">
                <el-option :label="item.label" :value="item.value" v-for="(item,index) in signTypeOptionsArr" :key="index" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="签约(竞选)方式" v-if="form.contractTemplateId!=5">
              <el-select disabled class="common-width" v-model="form.competitionLeaseType" placeholder="请选择">
                <el-option :label="item.label" :value="item.value" v-for="(item,index) in competeTypeOptionsArr" :key="index" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="保证金(元)" v-if="form.contractTemplateId!=5">
          <el-input disabled v-model="form.deposit" class="common-width" placeholder="请输入保证金"></el-input>
        </el-form-item>
      </el-form>
    </el-card>
    <div class="button-wrapper">
      <el-button @click="goBack">返回上一级</el-button>
      <el-button @click="saveAndNext" color="#FF7B50" style="color: #fff;">保存并下一步</el-button>
    </div>
  </div>
</template>

<script setup>
import CommonTitle from "@/components/CommonTitle";
import {ElCard,ElForm,ElFormItem,ElInput,ElSelect,ElOption,ElRow,ElCol} from "element-plus";
import {ref,reactive,onMounted} from "vue";
import {localGet} from "@/common/utils/GlobalUtils";
import {useRouter} from "vue-router";
import {contractApi} from "@/api/assets";
import {competeTypeOptionsArr,signTypeOptionsArr} from "@/common/dict/dictCollect";
import store from "@/store";
import {fundManagementApi} from "@/api/businessFinance";

const contractId = ref('');
const form = reactive({
  projectSetId:'',//项目集
  projectId:'', // 项目id
  contractName: '',// 合同名称 *
  deposit: '', // 押金（元）*
  competitionLeaseType: '',// 竟租类型（1公开竟租 2线下竟租）*
  signType: '', // 签约类型(1新签2续签) *
  projectName:'',// 项目名称 *
  // meetingId:'1',//会议编号（任务来源） *
  meetingTitle:'',// 任务来源 *
  contractId:'',// 合同编号 *
  payeeDay:'',// 收款预警天数
  contractDay:'',// 合同到期提醒天数
  returnDay:'',// 逾期归还提醒天数
  contractTemplateId:'',// 合同模板编号
});
const rules = reactive({
    contractName: [
        { required: true, message: '合同名称不能为空!', trigger: 'blur' },
    ],
    projectId: [
        { required: true, message: '请选择项目!', trigger: 'change' },
    ],
    projectSetId: [
        { required: true, message: '请选择项目集!', trigger: 'change' },
    ],
    meetingTitle: [
        { required: true, message: '任务来源不能为空!', trigger: 'blur' },
    ],
});

const emits = defineEmits(['nextStep']);
const goBack = ()=>{
  emits('nextStep','GoEdit');
}

const elFormRef = ref(null);
const saveAndNext = ()=>{
  elFormRef.value.validate((valid, fields)=>{
    if (valid) {
      contractApi.saveReplenishInfo(form).then(res=>{
        if(res.code === '200'){
          store.commit('SET_XIN_ZU_SUPPLEMENTARY_AGREEMENT_FORM',form);
          emits('nextStep','GoSubmit');
        }
      });
    } else {
      console.log('error submit!', fields)
    }
  });
}

const router = useRouter();
const contractTemplateId = router.currentRoute.value.params.contractTemplateId;
const getReplenishInfo = (contractId) =>{
  contractApi.getReplenishInfo({
    contractId:contractId
  }).then(res=>{
    if(res.code==='200'){
      // form.contractName = res.data.contractName;
      form.deposit = res.data.deposit;
      form.competitionLeaseType = res.data.competitionLeaseType;
      form.signType = res.data.signType;
      // form.projectName = res.data.projectName;
      form.contractId = res.data.contractId;
      // form.payeeDay = res.data.payeeDay;
      // form.contractDay = res.data.contractDay;
      // form.returnDay = res.data.returnDay;
      // form.meetingTitle  =res.data.meetingTitle;
      form.contractTemplateId = contractTemplateId;
    }
  });
}

const initForm = () => {
  if(JSON.stringify(store.state.collaborativeApproval.xinZuSupplementaryAgreementForm)!=='{}' && store.state.collaborativeApproval.xinZuSupplementaryAgreementForm!==''){
      for(let key in JSON.parse(JSON.stringify(store.state.collaborativeApproval.xinZuSupplementaryAgreementForm))){
          form[key] = store.state.collaborativeApproval.xinZuSupplementaryAgreementForm[key];
          if(store.state.collaborativeApproval.xinZuSupplementaryAgreementForm['projectSetId']){
              getProjects(store.state.collaborativeApproval.xinZuSupplementaryAgreementForm['projectSetId']);
          }
      }
  }
}


const projectSetList = ref([]);
const getProjectSets = () => {
    fundManagementApi.getProjectSets().then((res) => {
        projectSetList.value = res.data;
    });
};

const projectList = ref([]);
const getProjects = (projectSetId) => {
    fundManagementApi.getProjects(projectSetId).then((res) => {
        projectList.value  = res.data;
    });
};

/**
 * 项目集
 * @param e
 */
const projectSetIdChange = (e) => {
    form.projectId = '';
    if(e){
        getProjects(e);
    }
}

/**
 * 项目
 */
const changeProject = (e) => {
    form.projectName = '';
    let i = projectList.value.findIndex(x=>x.projectId===e);
    if(e && i!==-1){
        form.projectName =  projectList.value[i].projectName;
    }
    store.commit('SET_XIN_ZU_SUPPLEMENTARY_AGREEMENT_FORM',form);
}


onMounted(()=>{
  contractId.value = localGet('contractId');
  getReplenishInfo(contractId.value);
  initForm();
  getProjectSets();
});
</script>

<style lang="scss" scoped>
.container{
  .card-box{
    .common-width{
      width: 300px;
    }
    .contractName{
      width: 548px;
    }
    .projectName{
      width: 548px;
    }
    .earnest-money{
      width: 548px;
    }
  }
  .button-wrapper{
    display: flex;
    justify-content: center;
    margin-top: 30px;
  }
}
</style>
